import { ensureArray } from "@/api/_helpers";

export interface MediaAttachment {
  images: string[];
  videos: string[];
}

export interface ParticipantRef {
  id: number | null;
  org_id: number | null;
  name: string;
}

export interface AssistUserRef {
  id: number;
  name: string;
}

export interface RegionRef {
  id: number;
  name: string;
}

export interface ProductPreview {
  id: number;
  title: string;
  model: string;
}

export const toOptionalNumber = (value: unknown): number | null => {
  if (value === undefined || value === null || value === "") return null;
  const num = Number(value);
  return Number.isFinite(num) ? num : null;
};

export const mapMedia = (value: unknown): MediaAttachment => {
  if (!value) {
    return { images: [], videos: [] };
  }

  if (Array.isArray(value)) {
    const list = ensureArray<string>(value).filter(Boolean);
    return { images: list, videos: [] };
  }

  if (typeof value !== "object") {
    const text = String(value);
    return text ? { images: [text], videos: [] } : { images: [], videos: [] };
  }

  const record = value as Record<string, any>;

  const images = ensureArray<string>(
    record.images ?? record.img ?? record.photos ?? record.pictures ?? []
  ).filter(Boolean);

  const videos = ensureArray<string>(
    record.videos ?? record.video ?? record.media_videos ?? []
  ).filter(Boolean);

  return {
    images,
    videos
  };
};

export const mapParticipant = (
  source: Record<string, any> | undefined,
  fallbackId: unknown,
  fallbackOrgId: unknown
): ParticipantRef => {
  const id = toOptionalNumber(source?.id ?? fallbackId);
  const orgId = toOptionalNumber(source?.org_id ?? fallbackOrgId);

  return {
    id,
    org_id: orgId,
    name: source?.name ?? ""
  };
};

export const cleanupQuery = (source: Record<string, any>) => {
  const result: Record<string, any> = {};
  Object.entries(source).forEach(([key, value]) => {
    if (value === "" || value === undefined || value === null) return;
    result[key] = value;
  });
  return result;
};
